package com.ella.common.security.handler;
import com.alibaba.fastjson2.JSON;
import com.ella.common.constants.RedisConstants;
import com.ella.entity.security.LoginUser;
import com.ella.utils.JwtUtil;
import com.ella.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

	@Resource
	private RedisCache redisCache;

	@Override
	public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
		// TODO 从请求头中获取token
		String token = httpServletRequest.getHeader("token");
		try {
			LoginUser loginUser = JwtUtil.parseJWT(token);

			if (loginUser != null) {
				Long userId = loginUser.getUserId();
				//删除redis中封装的用户信息
				redisCache.deleteObject(RedisConstants.LOGIN_USER_INFO_STORE_PRE + userId);
				//删除用户登录次数缓存
				redisCache.deleteObject(RedisConstants.LOGIN_TRY_KEY_PRE + userId);
			}

		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
}